package com.springboot.personblogsystem.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.personblogsystem.common.req.UserRegisterParam;
import com.springboot.personblogsystem.mapper.UserMapper;
import com.springboot.personblogsystem.common.Result;
import com.springboot.personblogsystem.model.User;
import com.springboot.personblogsystem.common.req.UserLoginParam;
import com.springboot.personblogsystem.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.springboot.personblogsystem.common.Constants.SALT;
import static com.springboot.personblogsystem.common.Constants.USERINFO;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-14
 * Time: 9:19
 */
@Slf4j
@Service
public class UserServiceImp implements UserService {

    @Resource
    private UserMapper userMapper;

    // 用户登录
    @Override
    public Result<Boolean> userLogin(UserLoginParam userLoginParam, HttpSession session) {
        // 1、校验参数是否为空
        if (userLoginParam == null
                || !StringUtils.hasText(userLoginParam.getUserName())
                || !StringUtils.hasText(userLoginParam.getPassword())) {
            log.info("[userLogin]: 参数不合法");
            return Result.error("参数不合法", false);
        }
        // 2、判断用户名是否包含特殊字符(非数字、字母、中文以外的字符)
        String userName = userLoginParam.getUserName();;
        if(!userName.matches("[a-zA-Z0-9\\u4e00-\\u9fa5]+")) {
            log.info("[userLogin]: 用户名包含特殊字符");
            return Result.error("用户名包含特殊字符", false);
        }
        // 3、查询数据库是否存在该用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        List<User> userList = userMapper.selectList(queryWrapper);
        if (userList.size() == 0) {
            log.info("[userLogin]: 用户不存在");
            return Result.error("用户不存在", false);
        }
        // 注册确保不能出现同名的用户
        User user = userList.get(0);
        // 4、对密码进行加盐、加密，然后判断数据库中存放的结果是否一致
        // 1)加盐
        String newPasswordBySALT = SALT + userLoginParam.getPassword() + SALT;
        // 2)加密
        String newPasswordByEncrypt = DigestUtils.
                md5DigestAsHex(newPasswordBySALT.getBytes(StandardCharsets.UTF_8));
        if (!newPasswordByEncrypt.equals(user.getPassword())) {
            log.info("[userLogin]: 密码错误");
            return Result.error("密码错误", false);
        }
        // 将用户信息脱敏，并存储到session中
        user.setPassword("");
        session.setAttribute(USERINFO, user);
        log.info("[userLogin]: "+userName+" 登录成功");
        return Result.success(true);
    }

    @Override
    public Result<Boolean> userRegister(UserRegisterParam userRegisterParam) {
        // 1、校验参数是否为空
        if (userRegisterParam == null
                || !StringUtils.hasText(userRegisterParam.getUserName())
                || !StringUtils.hasText(userRegisterParam.getPassword())) {
            log.info("[userRegister]: 参数不合法");
            return Result.error("参数不合法", false);
        }
        // 2、判断用户名是否包含特殊字符(非数字、字母、中文以外的字符)
        String userName = userRegisterParam.getUserName();;
        if(!userName.matches("[a-zA-Z0-9\\u4e00-\\u9fa5]+")) {
            log.info("[userRegister]: 用户名包含特殊字符");
            return Result.error("用户名包含特殊字符", false);
        }
        // 3、查询数据库看该用户名是否已经被注册了
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        List<User> userList = userMapper.selectList(queryWrapper);
        if (userList.size() != 0) {
            log.info("[userRegister]: "+userName+" 无法重复注册");
            return Result.error(userName+"无法重复注册", false);
        }
        // 4、对密码进行加盐、加密，然后判断数据库中存放的结果是否一致
        // 1)加盐
        String newPasswordBySALT = SALT + userRegisterParam.getPassword() + SALT;
        // 2)加密
        String newPasswordByEncrypt = DigestUtils.
                md5DigestAsHex(newPasswordBySALT.getBytes(StandardCharsets.UTF_8));
        // 用户信息存储到数据库中
        User user = new User();
        user.setUserName(userName);
        user.setPassword(newPasswordByEncrypt);
        // 默认设置为百度链接
        user.setGitee("https://www.baidu.com/");
        int result = userMapper.insert(user);
        if (result != 1) {
            log.info("[userRegister]: 注册失败");
            return Result.error("注册失败", false);
        }
        log.info("[userRegister]: "+userName+" 注册成功");
        return Result.success(true);
    }

    @Override
    public Result<User> getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(USERINFO) == null) {
            log.info("[getUserInfo]: 用户并未登录");
            return Result.error("用户并未登录", null);
        }
        return Result.success((User) session.getAttribute(USERINFO));
    }

    @Override
    public Result<Boolean> deleteUserSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(USERINFO) == null) {
            log.info("[deleteUserSession]: 用户并未登录");
            return Result.error("用户并未登录", false);
        }
        String userName = ((User) session.getAttribute(USERINFO)).getUserName();
        // 清除session信息
        session.invalidate();
        log.info("[deleteUserSession]: "+userName+" 成功退出");
        return Result.success(true);
    }
}
